import { useRef, useState, useEffect } from "react";
import {
  Button,
  Form,
  Input,
  Modal,
  Space,
  Upload,
  UploadFile,
  UploadProps,
  message,
  notification,
} from "antd";
import { LeftCircleOutlined } from "@ant-design/icons";
import NewsEditor from "@/components/NewsEditor";
import { NavLink, useParams } from "react-router-dom";
import { RcFile } from "antd/es/upload";
import styles from "./index.module.scss";
import { getNewsDesc, putNews, addFiles } from "@/request/api";
import { getFormatTime } from "@/utils";

export default function NewsUpdate() {
  const NewsForm: any = useRef(null);
  const [content, setContent] = useState("");
  const [formInfo, setFormInfo]: any = useState({});
  const [isSureOpen, setIsSureOpen]: any = useState(false);
  const [dataList, setDataList]: any = useState([]);
  const [imgURL, setImgURL]: any = useState("");

  // 上传轮播图片
  const [fileValue, steFileValue]: any = useState(""); //接口返回的保存地址和文件名称
  const handleChange: UploadProps["onChange"] = (item: any) => {
    // 限制上传格式
    const isJpgOrPng =
      item.file.type === "image/jpeg" || item.file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("You can only upload JPG/PNG file!");
      return;
    }
    // 调用上传接口
    const formData = new FormData();
    formData.append("file_type", "cover");
    formData.append("file", item.file);
    addFiles(formData).then((res: any) => {
      if (res && res[0] && res[0].fileId) {
        steFileValue(res[0].fileId);
      }
    });
  };
  // 获取表单内容
  const params = useParams();
  useEffect(() => {
    getNewsDesc(params.id).then((res: any) => {
      setDataList(res);
      NewsForm.current.setFieldsValue({
        title: res.title,
        created_at: getFormatTime(res.created_at),
      });
      setContent(res.content);
      setImgURL(res.cover);
    });
  }, [params.id]);
  // 更新
  const handleOK = () => {
    NewsForm.current
      .validateFields()
      .then((res: any) => {
        setFormInfo(res);
        setIsSureOpen(true);
      })
      .catch((error: any) => {
        console.log(error);
        message.error("请填写必填项");
      });
  };
  //   取消更新
  const handleCancel = () => {
    setIsSureOpen(false);
    setPreviewOpen(false);
  };
  //   确认更新
  const handleYes = () => {
    if (content === "" || content.trim() === "<p></p>") {
      message.error("内容不能为空");
    } else {
      return new Promise((resolve, reject) => {
        putNews(dataList.id, {
          title: formInfo.title,
          content: content,
          is_top: 0,
          status: "published",
          cover: fileValue ? fileValue : imgURL,
        }).then((res: any) => {
          if (res.code === 404) {
            message.error("无相关资源");
          } else {
            notification.info({
              message: `通知`,
              description: "操作成功",
              placement: "bottomRight",
            });
            setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
            location.href = `/newsConfig`;
          }
        });
      });
    }
  };
  // 图片预览
  const getBase64 = (file: RcFile): Promise<string> =>
    new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = (error) => reject(error);
    });
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState("");
  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as RcFile);
    }
    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
  };

  return (
    <div
      style={{
        backgroundColor: "#c1e1fd",
        minHeight: "100vh",
        padding: "30px",
      }}
    >
      <div className={styles.addStyle}>
        <div style={{ display: "flex", justifyContent: "space-between" }}>
          <div style={{ display: "flex" }}>
            <LeftCircleOutlined
              onClick={() => {
                window.history.back();
              }}
              className={styles.handleBack}
            />
            <Form
              ref={NewsForm}
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 16 }}
              initialValues={{ creatTime: "2024-5-30" }}
            >
              <Space direction="horizontal" size={90}>
                <Form.Item
                  name="title"
                  label="新闻标题"
                  labelCol={{ span: 8 }}
                  rules={[
                    {
                      required: true,
                      message: "请输入新闻标题！",
                    },
                  ]}
                >
                  <Input style={{ width: 160 }} />
                </Form.Item>

                <Form.Item
                  name="created_at"
                  label="创建时间"
                  labelCol={{ span: 8 }}
                >
                  <Input
                    style={{
                      width: 160,
                    }}
                    disabled
                  />
                </Form.Item>

                <Form.Item
                  name="cover"
                  label="新闻封面"
                  valuePropName="cover"
                  labelCol={{ span: 25 }}
                >
                  <Upload
                    onChange={handleChange}
                    onPreview={handlePreview}
                    beforeUpload={() => {
                      return false;
                    }}
                    maxCount={1}
                  >
                    <div
                      style={{
                        width: 80,
                        border: "1px solid black",
                        textAlign: "center",
                        cursor: "pointer",
                        marginLeft: "15px",
                      }}
                    >
                      选择文件
                    </div>
                  </Upload>
                </Form.Item>
              </Space>
            </Form>
          </div>

          <div style={{ display: "flex" }}>
            <NavLink
              to={`/newsConfig/newsPreview/${params.id}`}
              className={styles.previewBtn}
            >
              <Button>预览</Button>
            </NavLink>
            <Button type="primary" onClick={() => handleOK()}>
              保存
            </Button>
          </div>
        </div>

        <NewsEditor
          getContent={(value: any) => {
            setContent(value);
          }}
          content={content}
        ></NewsEditor>

        <Modal
          title="更新"
          open={isSureOpen}
          onOk={handleYes}
          onCancel={handleCancel}
        >
          <p>你确定更新吗</p>
        </Modal>
        {/* 图片预览 */}
        <Modal open={previewOpen} footer={null} onCancel={handleCancel}>
          <img alt="example" style={{ width: "100%" }} src={previewImage} />
        </Modal>
      </div>
    </div>
  );
}
